// 产品数据存储服务
// 导入ApiService
import ApiService from './ApiService.js';

class ProductStore {
  constructor() {
    this.products = [];
    this.listeners = [];
    this.isLoading = false;
    this.error = null;
    
    // 从localStorage加载数据作为初始数据
    this.loadFromStorage();
  }
  
  // 从API加载数据
  async loadProducts() {
    this.isLoading = true;
    this.error = null;
    try {
      const response = await ApiService.getProducts();
      if (response.success) {
        this.products = response.data;
        this.saveToStorage(); // 缓存到本地
        this.notifyListeners();
        return true;
      } else {
        throw new Error('Failed to load products');
      }
    } catch (error) {
      console.error('Failed to load products from API:', error);
      this.error = error.message || '加载产品数据失败';
      // 如果API失败，确保我们有数据可用
      if (this.products.length === 0) {
        this.loadFromStorage();
      }
      return false;
    } finally {
      this.isLoading = false;
    }
  }
  
  // 添加监听器
  addListener(listener) {
    this.listeners.push(listener);
  }
  
  // 移除监听器
  removeListener(listener) {
    this.listeners = this.listeners.filter(l => l !== listener);
  }
  
  // 通知所有监听器数据已更新
  notifyListeners() {
    this.listeners.forEach(listener => listener());
  }
  
  // 保存数据到localStorage
  saveToStorage() {
    localStorage.setItem('productsData', JSON.stringify(this.products));
  }
  
  // 从localStorage加载数据
  loadFromStorage() {
    const savedData = localStorage.getItem('productsData');
    if (savedData) {
      try {
        this.products = JSON.parse(savedData);
      } catch (e) {
        console.error('Failed to load products from localStorage:', e);
      }
    }
  }
  
  // 获取所有产品
  getAllProducts() {
    return [...this.products];
  }
  
  // 获取上架的产品
  getActiveProducts() {
    return this.products.filter(product => product.status === 'active');
  }
  
  // 根据ID获取产品
  getProductById(id) {
    return this.products.find(product => product.id === id);
  }
  
  // 根据分类获取产品
  getProductsByCategory(category) {
    return this.products.filter(product => product.category === category);
  }
  
  // 添加产品
  async addProduct(product) {
    try {
      const response = await ApiService.addProduct(product);
      if (response.success) {
        this.products.push(response.data);
        this.saveToStorage();
        this.notifyListeners();
        return response.data;
      } else {
        throw new Error('Failed to add product');
      }
    } catch (error) {
      console.error('Failed to add product via API:', error);
      // API失败时的降级处理
      const newId = Math.max(0, ...this.products.map(p => p.id)) + 1;
      const newProduct = {
        id: newId,
        ...product
      };
      this.products.push(newProduct);
      this.saveToStorage();
      this.notifyListeners();
      return newProduct;
    }
  }
  
  // 更新产品
  async updateProduct(id, updatedProduct) {
    try {
      const response = await ApiService.updateProduct(id, updatedProduct);
      if (response.success) {
        const index = this.products.findIndex(p => p.id === id);
        if (index !== -1) {
          this.products[index] = response.data;
          this.saveToStorage();
          this.notifyListeners();
          return response.data;
        }
      } else {
        throw new Error('Failed to update product');
      }
    } catch (error) {
      console.error('Failed to update product via API:', error);
      // API失败时的降级处理
      const index = this.products.findIndex(p => p.id === id);
      if (index !== -1) {
        this.products[index] = {
          ...this.products[index],
          ...updatedProduct
        };
        this.saveToStorage();
        this.notifyListeners();
        return this.products[index];
      }
    }
    return null;
  }
  
  // 删除产品
  async deleteProduct(id) {
    try {
      const response = await ApiService.deleteProduct(id);
      if (response.success) {
        const initialLength = this.products.length;
        this.products = this.products.filter(product => product.id !== id);
        
        if (this.products.length !== initialLength) {
          this.saveToStorage();
          this.notifyListeners();
          return true;
        }
      } else {
        throw new Error('Failed to delete product');
      }
    } catch (error) {
      console.error('Failed to delete product via API:', error);
      // API失败时的降级处理
      const initialLength = this.products.length;
      this.products = this.products.filter(product => product.id !== id);
      
      if (this.products.length !== initialLength) {
        this.saveToStorage();
        this.notifyListeners();
        return true;
      }
    }
    return false;
  }
  
  // 搜索产品
  searchProducts(query) {
    if (!query) {
      return this.getAllProducts();
    }
    
    const lowerQuery = query.toLowerCase();
    return this.products.filter(product => 
      product.name.toLowerCase().includes(lowerQuery) ||
      product.description.toLowerCase().includes(lowerQuery)
    );
  }
  
  // 获取产品分类列表
  getCategories() {
    const categories = [...new Set(this.products.map(product => product.category))];
    return categories;
  }
  
  // 获取各分类产品数量统计
  getCategoryStats() {
    const stats = {};
    this.products.forEach(product => {
      if (!stats[product.category]) {
        stats[product.category] = 0;
      }
      stats[product.category]++;
    });
    return stats;
  }
  
  // 获取产品总销售额统计
  getSalesStats() {
    const activeProducts = this.getActiveProducts();
    const totalStock = activeProducts.reduce((sum, product) => sum + product.stock, 0);
    const totalValue = activeProducts.reduce((sum, product) => sum + (product.price * product.stock), 0);
    
    return {
      totalProducts: activeProducts.length,
      totalStock,
      totalValue
    };
  }
  
  // 获取最近添加的产品
  getRecentProducts(limit = 5) {
    return [...this.products]
      .sort((a, b) => b.id - a.id)
      .slice(0, limit);
  }
  
  // 上传图片
  async uploadImage(file) {
    try {
      const response = await ApiService.uploadFile(file);
      if (response.success && response.data && response.data.url) {
        return response.data.url;
      } else {
        throw new Error('Failed to upload image');
      }
    } catch (error) {
      console.error('Failed to upload image via API:', error);
      // 生成模拟图片URL作为降级方案
      return `https://via.placeholder.com/300/4285f4/ffffff?text=${encodeURIComponent(file.name || 'Uploaded+Image')}`;
    }
  }
  
  // 获取产品统计数据
  async getProductStats() {
    try {
      const response = await ApiService.getStats();
      if (response.success) {
        return response.data;
      } else {
        throw new Error('Failed to get product stats');
      }
    } catch (error) {
      console.error('Failed to get product stats via API:', error);
      // API失败时，本地计算统计数据
      const activeProducts = this.getActiveProducts();
      const totalStock = activeProducts.reduce((sum, product) => sum + (product.stock || 0), 0);
      const totalValue = activeProducts.reduce((sum, product) => sum + ((product.price || 0) * (product.stock || 0)), 0);
      const categoryStats = this.getCategoryStats();
      
      return {
        totalProducts: this.products.length,
        activeProducts: activeProducts.length,
        inactiveProducts: this.products.length - activeProducts.length,
        totalStock,
        totalValue,
        categories: Object.entries(categoryStats).map(([name, count]) => ({ name, count }))
      };
    }
  }
  
  // 获取产品分类统计（兼容原方法）
  getCategoryStats() {
    const stats = {};
    this.products.forEach(product => {
      if (!stats[product.category]) {
        stats[product.category] = 0;
      }
      stats[product.category]++;
    });
    return stats;
  }
  
  // 添加分类
  async addCategory(categoryName) {
    try {
      // 检查分类是否已存在
      const categories = this.getCategories();
      if (categories.includes(categoryName.trim())) {
        throw new Error('分类已存在');
      }
      
      // 创建一个示例产品来保存新分类（因为分类是通过产品数据提取的）
      const newId = Math.max(0, ...this.products.map(p => p.id)) + 1;
      const exampleProduct = {
        id: newId,
        name: `示例产品 - ${categoryName}`,
        category: categoryName.trim(),
        price: 0,
        stock: 0,
        status: 'inactive',
        description: `这是${categoryName}分类的示例产品`,
        jdLink: '',
        taobaoLink: '',
        douyinLink: '',
        videoUrl: '',
        images: []
      };
      
      // 使用API添加示例产品
      const response = await ApiService.addProduct(exampleProduct);
      if (response.success) {
        this.products.push(response.data);
        this.saveToStorage();
        this.notifyListeners();
        return { success: true, category: categoryName.trim() };
      } else {
        throw new Error('添加分类失败');
      }
    } catch (error) {
      console.error('Failed to add category:', error);
      
      // API失败时的降级处理
      const categories = this.getCategories();
      if (categories.includes(categoryName.trim())) {
        return { success: false, error: '分类已存在' };
      }
      
      // 创建示例产品并添加到本地
      const newId = Math.max(0, ...this.products.map(p => p.id)) + 1;
      const exampleProduct = {
        id: newId,
        name: `示例产品 - ${categoryName}`,
        category: categoryName.trim(),
        price: 0,
        stock: 0,
        status: 'inactive',
        description: `这是${categoryName}分类的示例产品`,
        jdLink: '',
        taobaoLink: '',
        douyinLink: '',
        videoUrl: '',
        images: []
      };
      
      this.products.push(exampleProduct);
      this.saveToStorage();
      this.notifyListeners();
      return { success: true, category: categoryName.trim() };
    }
  }
  
  // 删除分类
  async deleteCategory(categoryName) {
    try {
      // 检查分类是否存在
      const categories = this.getCategories();
      if (!categories.includes(categoryName)) {
        throw new Error('分类不存在');
      }
      
      // 删除该分类下的所有产品
      this.products = this.products.filter(product => product.category !== categoryName);
      this.saveToStorage();
      this.notifyListeners();
      return true;
    } catch (error) {
      console.error('Failed to delete category:', error);
      return false;
    }
  }
}

// 创建单例实例
export default new ProductStore();